package com.miracle.common.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.miracle.common.R;


/**
 * NumEditText.java
 * 带有计数的EditText
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/6/9 11:06
 */
public class NumEditText extends LinearLayout implements TextWatcher {

    private static final int MAX_NUM = 100;

    private Context mContext;
    private TextView mTvNum;
    private EditText mEdittext;

    private String mString;

    private int mMaxNum = MAX_NUM;

    public NumEditText(Context context) {
        this(context, null);
    }

    public NumEditText(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NumEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    public int setLayoutId() {
        return R.layout.common_view_num_edittext;
    }

    private void init() {
        View view = LayoutInflater.from(mContext).inflate(setLayoutId(), this);
        mEdittext = view.findViewById(R.id.et);
        mTvNum = view.findViewById(R.id.tv_num);
        mEdittext.addTextChangedListener(this);
        mTvNum.setText("0/" + mMaxNum);
    }

    /**
     * 设置EditText最大显示长度
     * @param num
     */
    public void setMaxNum(int num) {
        mEdittext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(num)});
        mMaxNum = num;
        mTvNum.setText("0/" + mMaxNum);
    }

    /**
     * 获取EditText
     * @return
     */
    public String getEditText() {
        if (mString == null) {
            return "";
        }
        return mString;
    }

    /**
     * 设置edittext是否可以点击
     * @param enable
     */
    public void setEdittextEnable(boolean enable) {
        mEdittext.setFocusable(enable);
    }

    /**
     * 获取Edittext
     * @return
     */
    public EditText getEdittextView() {
        return mEdittext;
    }

    /**
     * 设置字符串
     * @param text
     */
    public void setEditTextText(String text) {
        mEdittext.setText(text);
    }

    /**
     * 设置hint
     * @param hintString
     */
    public void setHintString(String hintString) {
        mEdittext.setHint(hintString);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        mTvNum.setText(s.length() + "/" + mMaxNum);
        mString = s.toString();
    }
}
